package com.jpress.ejb;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.jpress.remote.DaoJpaBeanRemote;

@Stateless(mappedName="bean/daojpa")
public class DaoJpaBean<T> implements DaoJpaBeanRemote<T>, Serializable {

	private static final long serialVersionUID = 1L;
	@PersistenceContext(unitName="jpressEE") protected EntityManager em;
	
	@Override
	public void persist(Object obj) {
		em.persist(obj); 
	}
	
	@Override
	public void remove(Object obj) {
		em.remove(obj);
		em.flush();
	}
	
	@Override
	public void merge(Object obj) {
		em.merge(obj); 
	}	
	
	protected T find(Class<T> classe, Object chave) {
		return em.find(classe, chave);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> namedQueryResultList(String queryName) {
		return (List<T>) em.createNamedQuery(queryName).getResultList();
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<T> namedQueryResultList(String queryName, Map parameters) {
		Query q = em.createNamedQuery(queryName);
		@SuppressWarnings("unchecked")
		Set<String> chaves = parameters.keySet();
		for(String chave : chaves){
			if(chave != null){
				q.setParameter(chave, parameters.get(chave));
			}
		}
		@SuppressWarnings("unchecked")
		List<T> resultado = (List<T>) q.getResultList();
		return resultado;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T namedQuerySingleResult(String queryName) {
		List<T> resultado = em.createNamedQuery(queryName).getResultList();
		if(resultado.size() > 0)
			return (T) resultado.get(0);
		return null;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public T namedQuerySingleResult(String queryName, Map parameters) {
		Query q = em.createNamedQuery(queryName);
		@SuppressWarnings("unchecked")
		Set<String> chaves = parameters.keySet();
		for(String chave : chaves){
			if(chave != null){
				q.setParameter(chave, parameters.get(chave));
			}
		}
		@SuppressWarnings("unchecked")
		List<T> resultado = (List<T>) q.getResultList();
		if(resultado.size() > 0)
			return (T) resultado.get(0);
		return null;
	}
}
